<template>
  <!--
    /**************/
    双击表格
    函数名: tabelDblclick,
    返回字段：{row, column, event}
    /**************/
    处理表格DATA函数
    参数名: handleTabelData
    回传参数: tabelData
    接收返回值: tabelData
    实例:(tabelList)=> tabelList.map(item=>({...item,a:1,b:2}))

    获取表格数据接口地址
    参数名: apiUrl
    类型: String
    参数说明: 接口地址，必传

    表格数据接口地址请求方式
    参数名: method
    类型：String
    参数说明: 请求方式，非必传，默认POST

    默认搜索参数
    参数名: defaultSearch
    类型: [Object]
    参数说明: {
      id: 搜索编码(唯一)|String,
      searchName: 搜索名称|String,
      commSql: 搜索条件拼接|JSON String,
    }

    与表格无关的操作按钮
    参数名: operationButtons
    类型: [Object]
    参数说明: {
      icon: 图标|String,
      label: 按钮名称|String,
      click: 点击事件|function,
    }

    表格行按钮
    参数名: tableButtons
    类型: [Object]
    参数说明: {
      width: 宽度|Number
      icon: 图标|String,
      label: 按钮名称|String,
      click: 点击事件|function,
    }
    /**************/
    多选操作按钮（插槽slot）
    插槽名: multiple
    回传参数: 钩中行 | [row]
    /**************/
  -->
  <div class="app-table-container">
    <div class="operationBar">
      <!-- v-if="defaultSearch.length"
        :command.sync="commonId"
        :custom-search="customSearch"
      -->
      <defaultScreen :default-search="defaultSearch" :menu-code="tableConfig.menuCode" :table-code="tableConfig.tableCode" @toSearch="toSearch" />
      <div class="setButtons">
        <el-button v-for="(item, index) in operationButtons" :key="index" plain size="mini" @click.native="item.click()">
          <i v-if="!item.label" :class="item.icon" />
          {{ item.label }}
        </el-button>
        <span v-if="operationButtons.length" class="division" />
        <el-dropdown placement="bottom" size="medium" @command="toGlobalSetTabel">
          <el-button plain size="medium">
            <i class="el-icon-more" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="setColumn">列设置</el-dropdown-item>
            <!-- <el-dropdown-item command="setImport">导入</el-dropdown-item> -->
            <!-- <el-dropdown-item command="setExport">导出</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="tableViewMain">
      <el-table
        v-if="tableConfig.visible"
        ref="advancedTable"
        :loading="tableConfig.loading"
        :data="tableConfig.list"
        :max-height="tableMaxHeight"
        :stripe="true"
        :border="true"
        row-key="code"
        header-cell-class-name="tableViewHeaderCell"
header-row-class-name="tableViewHeader"
        style="border-radius: 6px 6px 0 0"
        @row-dblclick="tabelDblclick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="item in tableConfig.columns" :key="item.code" show-overflow-tooltip :prop="item.code" :label="item.name" :width="item.width" :sortable="!!item.sortable">
          <template v-if="item.filterable" slot="header">
            <el-popover ref="popover" placement="bottom" width="250" trigger="click">
              <div class="tabelHearderSearch">
                <el-row :gutter="10">
                  <el-col :span="18">
                    <div @click.stop.prevent>
                      <div class="el-input el-input--mini el-input--suffix" style="width: 170px">
                        <input v-model="filterList[item.sortCode]" type="text" autocomplete="off" placeholder="请输入内容" class="el-input__inner" @keyup.enter="filterableItem(filterList[item.sortCode], item.sortCode)">
                      </div>
                      <!-- <el-input v-model="filterList[item.code]" :style="{width:'170px'}" placeholder="请输入内容" clearable @input="updateFilterableItem($event,item.code,'input')" @change="updateFilterableItem($event,item.code,'change')" /> -->
                      <!-- <el-input :style="{width:'170px'}" placeholder="请输入内容" clearable @keyup.enter.stop="filterableItem($event,item.code)" /> -->
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <el-button type="primary" icon="el-icon-search" @click="filterableItem(filterList[item.sortCode], item.sortCode)" />
                  </el-col>
                </el-row>
              </div>
              <div slot="reference" class="showMore" @click.stop>
                <span>{{ item.name }}</span>
                <i class="el-icon-search" />
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column v-if="tableButtons.length" fixed="right" label="操作" :width="computedButtonWidth">
          <template slot-scope="scope">
            <el-button v-for="(item, index) in tableButtons" :key="index" size="small" :icon="item.icon" @click.native.prevent="item.click(scope.row, scope.$index)">{{ item.label }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="footerColumnCard">
        <div class="checkbox">
          <el-checkbox v-model="tableConfig.tableCheckAll" :indeterminate="tableConfig.tableIsIndeterminate" @change="advancedTableSclected">全选</el-checkbox>
          <p class="sclected">
            已选
            <span>{{ tableConfig.multipleSelection.length }}</span>条
          </p>
          <div class="divider" />
          <div class="buttons">
            <slot name="multiple" :multiple="tableConfig.multipleSelection" />
          </div>
        </div>
        <div class="pagination">
          <el-pagination background :current-page="pagination.current" :page-sizes="pagination.sizes" :page-size="pagination.size" :layout="pagination.layout" :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
    <setColumn :visible.sync="setColumnDialog.visible" :list="setColumnDialog.list" :options="setColumnDialog.widthOptions" @saveSetColumn="saveSetColumn" />
  </div>
</template>
<script>
import request from '@/utils/request'
import { queryTableColumn, queryconditionList, queryAdvanceExport, saveUserMenuExtensionsBatchSave, queryCommonCondition, saveCommonCondition, deleteCommonCondition } from '@/api/advanced'
import defaultScreen from './defaultScreen'
import setColumn from './setColumn'
export default {
  name: 'TabelMain',
  components: {
    defaultScreen,
    setColumn,
  },
  props: {
    handleTabelData: {
      type: Function,
      require: false,
      default: null,
    },
    apiUrl: {
      type: String,
      require: true,
      default: null,
    },
    method: {
      type: String,
      require: false,
      default: 'post',
    },
    defaultSearch: {
      type: Array,
      require: false,
      default: () => [],
    },
    tableCode: {
      type: String,
      require: false,
      default: '',
    },
    tableButtons: {
      type: Array,
      require: false,
      default: () => [],
    },
    operationButtons: {
      type: Array,
      require: false,
      default: () => [],
    },
  },
  data() {
    return {
      updateTime: '',
      // value: '',
      filterList: {
        updateTime: '',
      },
      isPopover: false,
      filterQueryBos: [],
      dynamicQueryBos: [],
      commonId: '',
      tableConfig: {
        multipleSelection: [],
        tableIsIndeterminate: false,
        tableCheckAll: false,
        visible: false,
        loading: true,
        buttonWidth: 0,
        buttons: [],
        list: [],
        columns: [],
        tableCode: this.tableCode || '',
        menuCode: this.$route.name,
      },
      pagination: {
        current: 1,
        total: 400,
        size: 100,
        sizes: [100, 200, 300, 400],
        layout: 'prev, pager, next, sizes',
      },
      setColumnDialog: {
        visible: false,
        list: [],
        widthOptions: [80, 100, 180],
      },
    }
  },
  computed: {
    computedButtonWidth() {
      // const def = this.tableConfig.buttonWidth
      const calculated = this.tableButtons.reduce((acc, cur) => {
        const w = cur.width || (cur.text ? 100 : 80)
        return acc + w
      }, 0)
      return calculated
    },
    tableMaxHeight() {
      return window.innerHeight - (94 + 36 + 30 + 52)
    },
  },
  watch: {
    tableCode(val) {
      const tableCode = val || this.$route.name
      this.tableConfig.tableCode = tableCode
    },
  },
  mounted() {
    this.queryColumns()
  },
  methods: {
    // showIsPopover() {
    //   console.log(this.tableConfig.columns)
    //   console.log(this.$refs.popover[0].$refs.popper)
    //   const pop = this.$refs.popover[0].$refs.popper
    //   this.findElTableBodyWrapper().appendChild(pop)
    // },
    findElTableBodyWrapper() {
      const dom = window.document.querySelector('.tableViewMain .el-table__body-wrapper')
      return dom
    },
    advancedTableSclected(is) {
      if (is) {
        this.$refs['advancedTable'].toggleAllSelection()
      } else {
        this.$refs['advancedTable'].clearSelection()
      }
    },
    filterableItem(input, code) {
      const find = this.filterQueryBos.find((item) => item.name === code)
      if (find) {
        find.value = input
      } else {
        const item = {
          name: code,
          operator: 'LIKE',
          type: 1,
          value: input,
          valueType: 1,
        }
        this.filterQueryBos.push(item)
      }
      this.pagination.current = 1
      this.getList()
    },
    toSearch(data) {
      this.dynamicQueryBos = data.dynamicQueryBos || []
      this.customSearch = data.customSearch || []
      this.commonId = data.commonId || ''
      this.pagination.current = 1
      this.getList()
    },
    getList() {
      const data = {
        dynamicQueryBos: this.dynamicQueryBos,
        pageNumber: this.pagination.current,
        commonId: this.commonId,
        filterQueryBos: this.filterQueryBos.filter((item) => item.value),
        pageSize: this.pagination.size,
        sortColumns: [],
      }
      const params = {
        url: this.apiUrl, // `/auth/demo/queryAdvanceUser`,
        method: this.method,
      }
      if (params.method === 'get') {
        params.params = data
      } else {
        params.data = data
      }
      request(params).then((res) => {
        // console.log(res)
        const { records, total, current } = res.data
        let list = []
        if (this.handleTabelData) {
          list = this.handleTabelData(records)
        } else {
          list = records
        }
        this.tableConfig.list = list
        this.pagination.pageNumber = current
        this.pagination.total = total
      })
    },
    // 获取表头数据
    queryColumns() {
      this.tableConfig.visible = false
      queryTableColumn({ menuCode: this.tableConfig.menuCode, tableCode: this.tableConfig.tableCode }).then((res) => {
        const list = res.data || []
        const filterList = {}
        list.map((el) => {
          if (el.filterable) {
            filterList[el.sortCode] = null
          }
        })
        this.filterList = filterList
        this.setColumnDialog.list = JSON.parse(JSON.stringify(list))
        this.tableConfig.columns = list
        this.$nextTick(() => {
          this.tableConfig.visible = true
        })
        this.getList()
      })
    },
    // 页码切换
    handleCurrentChange(current) {
      this.pagination.current = current
      this.getList()
    },
    // 每页显示切换
    handleSizeChange(size) {
      this.pagination.size = size
      this.getList()
    },
    // 表格勾选
    handleSelectionChange(val) {
      if (val.length === 0) {
        this.tableConfig.tableCheckAll = false
      } else {
        this.tableConfig.tableCheckAll = true
      }
      this.tableConfig.multipleSelection = val
    },
    // 双击表格
    tabelDblclick(row, column, event) {
      this.$emit('tabelDblclick', { row, column, event })
    },
    // 打开自定义列设置
    openSetColumn() {
      this.setColumnDialog.visible = true
    },
    // 更新主表格布局
    updateTabelLayout(data) {
      this.tableConfig.loading = true
      this.tableConfig.columns = data
      setTimeout(() => {
        this.tableConfig.loading = false
        this.tableConfig.visible = false
        this.$nextTick(() => {
          this.tableConfig.visible = true
        })
      }, 500)
    },
    // 保存自定义列
    saveSetColumn(data) {
      this.setColumnDialog.list = data
      this.setColumnDialog.visible = false
      this.updateTabelLayout(data)
    },
    // 所有表格下拉操作
    toGlobalSetTabel(name) {
      console.log(name)
      switch (name) {
        case 'setColumn':
          this.openSetColumn()
          break
      }
    },
  },
}
</script>
